'''https://blog.csdn.net/weixin_43495441/article/details/106519111'''
import random

'''
列表推导式： [表达式 for 变量 in 旧列表] 或者 [表达式 for 变量 in 旧列表 if 条件]
'''


def demo1():
    '''列表推导式'''
    list1 = [i for i in range(10)]
    print(list1)
    list2 = [i + 1 for i in list1]
    print(list2)
    list3 = [i for i in list1 if i > 3]
    print(list3)
    list4 = [i + 5 if i < 3 else i + 1 for i in list1]
    print(list4)

    '''list4等于'''
    list5 = []
    for i in list1:
        if i < 3:
            i = i + 5
        else:
            i = i + 1
        list5.append(i)
    print(list5)

    list6 = [f"{x} * {y} = {x * y}" for x in range(1, 9 + 1) for y in range(1, 9 + 1) if x <= y]
    print(list6)
    '''等于'''
    list7 = []
    for x in range(1, 9 + 1):
        for y in range(1, 9 + 1):
            if x <= y:
                list7.append(f"{x} * {y} = {x * y}")
    print(list7)


def demo2():
    '''字典推导式'''
    dict1 = {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'C'}
    dict1 = {value: key for (key, value) in dict1.items()}
    print(dict1)


def demo3():
    '''集合推导式'''
    list1 = [random.randint(0, 10) for i in range(10)]
    print(list1)
    set1 = {i for i in list1}
    print(set1)


def demo4():
    '''生成器'''
    gen = (i for i in range(10))
    print(type(gen))
    while True:
        try:
            print(next(gen))
        except Exception as e:
            print("已经不能继续迭代")
            break


if __name__ == '__main__':
    # demo1()
    # demo2()
    # demo3()
    demo4()